package com.demo.widget.meis;

import com.demo.widget.BaseAbility;
import com.demo.widget.ResourceTable;

import com.meis.widget.xiaohongshu.CoordinatorLinearLayout;
import com.meis.widget.xiaohongshu.CoordinatorRecyclerView;
import com.meis.widget.xiaohongshu.MCropImageView;

import cs.help.tool.Toast;

import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Point;
import ohos.agp.utils.Rect;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * Created by wenshi on 2019/3/1.
 * Description
 */
public class MeiCropImageAbility extends BaseAbility {
    private Component mToolbar;
    MCropImageView mMCropImageView;
    CoordinatorRecyclerView mRecyclerView;
    MyAdapter mMyAdapter;
    CoordinatorLinearLayout mCoordinatorLayout;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_mei_crop_ability);
        mToolbar = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_toolbar, null, false);
        mMCropImageView = (MCropImageView) findComponentById(ResourceTable.Id_crop_view);
        mMCropImageView.getDragImageHelper().setmMaxScale(3.73f);
        mRecyclerView = (CoordinatorRecyclerView) findComponentById(ResourceTable.Id_recycler);
        mCoordinatorLayout = (CoordinatorLinearLayout) findComponentById(ResourceTable.Id_coordinator_layout);
        ComponentContainer componentParent = (ComponentContainer) mCoordinatorLayout.getComponentParent();
        componentParent.addComponent(mToolbar);
        getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                mCoordinatorLayout.setPadding(0, mToolbar.getEstimatedHeight(), 0, 0);
            }
        }, 100);

        List<Integer> datas = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            datas.add(i % 2);
        }
        mRecyclerView.setItemProvider(mMyAdapter = new MyAdapter(getContext(), datas, 4));
        mMyAdapter.setImageClickListener((component, index) -> {
            mMCropImageView.setPixelMap(index % 2 == 0 ? ResourceTable.Media_ic_gril2 : ResourceTable.Media_ic_gril);
        });
        //         实现回调接口
        mRecyclerView.setOnCoordinatorListener(new CoordinatorRecyclerView.OnCoordinatorListener() {
            @Override
            public void onScroll(float y, float deltaY, int maxParentScrollRange) {
                mCoordinatorLayout.onScroll(y, deltaY, maxParentScrollRange);
            }

            @Override
            public void onFiling(int velocityY) {
                mCoordinatorLayout.onFiling(velocityY);
            }

            @Override
            public void handlerInvalidClick(int rawX, int rawY) {
                handlerRecyclerInvalidClick(mRecyclerView, rawX, rawY);
            }
        });

        mCoordinatorLayout.setOnScrollListener(new CoordinatorLinearLayout.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                ComponentContainer.LayoutConfig layoutConfig = mCoordinatorLayout.getLayoutConfig();
                layoutConfig.height = mCoordinatorLayout.getInitHeight() + scrollY;
                mCoordinatorLayout.setLayoutConfig(layoutConfig);
                mCoordinatorLayout.invalidate();
                mRecyclerView.setCurrentParenScrollY(scrollY);
                mRecyclerView.invalidate();
            }

            @Override
            public void isExpand(boolean isExpand) {
                mRecyclerView.setExpand(isExpand);
            }

            @Override
            public void completeExpand() {
                mRecyclerView.resetRecyclerHeight();
            }
        });
    }


    private void handlerRecyclerInvalidClick(ListContainer recyclerView, int touchX, int touchY) {
        if (recyclerView != null && recyclerView.getChildCount() > 0) {
            for (int i = 0; i < recyclerView.getChildCount(); i++) {
                Component childView = recyclerView.getComponentAt(i);
                if (childView != null) {
                    if (isTouchView(touchX, touchY, childView)) {
                        childView.simulateClick();
                        return;
                    }
                }
            }
        }
    }

    // 触摸点是否view区域内 parent.isPointInChildBounds(child, x, y)
    private boolean isTouchView(int touchX, int touchY, Component view) {
        Rect rect = new Rect();
        view.getWindowVisibleRect(rect);
        return rect.contains(touchX, touchY, touchX + 1, touchY + 1);
    }

    public static class MyAdapter extends CoordinatorRecyclerView.CoordinatorAdapter {
        private static final int GRID_MARGIN = 4;
        private final Context mContext;
        private final List<Integer> mDatas;
        private int numColumns;
        private ImageClickListener imageClickListener;

        public MyAdapter(Context context, List<Integer> data, int colums) {
            this.mContext = context;
            this.mDatas = data;
            this.numColumns = colums;
        }

        public void setImageClickListener(ImageClickListener listener) {
            imageClickListener = listener;
        }

        @Override
        public int getCount() {
            if (mDatas != null) {
                return mDatas.size() % numColumns == 0 ? mDatas.size() / numColumns : mDatas.size() / numColumns + 1;
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            if (mDatas != null && position >= 0 && position <= mDatas.size()) {
                return mDatas.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int pos) {
            return pos;
        }

        /**
         * 获取条目的宽度
         *
         * @return int
         */
        public int getSqureWidth() {
            DisplayManager displayManager = DisplayManager.getInstance();
            Optional<Display> optDisplay = displayManager.getDefaultDisplay(mContext);
            if (optDisplay.isPresent()) {
                Point point = new Point(0, 0);
                optDisplay.get().getRealSize(point);
                int screenWidth = (int) point.position[0];
                return Math.floorDiv(screenWidth, numColumns);
            }
            return 0;
        }

        @Override
        public int getAllLength() {
            return (getSqureWidth() + GRID_MARGIN) * getCount();
        }

        @Override
        public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
            ViewHolder holder;
            if (convertComponent == null) {
                ComponentContainer newComponent = (ComponentContainer) LayoutScatter.getInstance(mContext).parse(
                        ResourceTable.Layout_item_coordinator_layout, null, false);
                setConvertComponentConfig(newComponent);
                holder = new ViewHolder(newComponent);
                int itemWidth = getSqureWidth();
                for (int i = 0; i < numColumns; i++) {
                    Image image = new Image(mContext);
                    image.setTag(position);
                    setChildComponentConfig(itemWidth, image);
                    newComponent.addComponent(image);
                    if (position * numColumns + i < mDatas.size()) {
                        setPixelMapByResId(position, i, image);
                        setClickListenerOnImage(position, i, image);
                    }
                }
                newComponent.setTag(holder);
                return newComponent;
            } else {
                // reuse the convertComponent which has been constructed before.
                holder = (ViewHolder) convertComponent.getTag();
                for (int i = 0; i < numColumns; i++) {
                    Image image = (Image) holder.getView(i);
                    image.setTag(position);
                    int imageIndex = position * numColumns + i;
                    if (imageIndex < mDatas.size()) {
                        setPixelMapByResId(position, i, image);
                        setClickListenerOnImage(position, i, image);
                    } else {
                        // clear the clickedListener for the blank position in last row
                        image.setClickedListener(null);
                    }
                }
                convertComponent.setTag(holder);
                return convertComponent;
            }
        }

        private void setChildComponentConfig(int itemSize, Image image) {
            image.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            ComponentContainer.LayoutConfig imageLayoutConfig = image.getLayoutConfig();
            imageLayoutConfig.width = itemSize;
            imageLayoutConfig.height = itemSize;
            imageLayoutConfig.setMarginBottom(GRID_MARGIN);
            imageLayoutConfig.setMarginRight(GRID_MARGIN);
            image.setLayoutConfig(imageLayoutConfig);
        }

        private void setConvertComponentConfig(Component convertComponent) {
            ((DirectionalLayout) convertComponent).setOrientation(Component.HORIZONTAL);
            ComponentContainer.LayoutConfig layoutConfig = convertComponent.getLayoutConfig();
            layoutConfig.width = DirectionalLayout.LayoutConfig.MATCH_PARENT;
            layoutConfig.height = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
            convertComponent.setLayoutConfig(layoutConfig);
        }

        private void setClickListenerOnImage(int position, int i, Image image) {
            image.setClickedListener(
                    component -> {
                        if (imageClickListener != null) {
                            imageClickListener.onImageClick(component, position * numColumns + i);
                            Toast.show(mContext, "click position = " + (position * numColumns + i));
                        }
                    });
        }

        private void setPixelMapByResId(int position, int i, Image image) {
            int imageIndex = position * numColumns + i;
            Integer imageId = mDatas.get(imageIndex);
            int resId = imageId == 0 ? ResourceTable.Media_icon_gril_2 : ResourceTable.Media_icon_girl_1;
            image.setPixelMap(resId);
        }

        public interface ImageClickListener {
            void onImageClick(Component component, int index);
        }

        public static class ViewHolder {
            private final ComponentContainer convertComponent;

            ViewHolder(Component component) {
                this.convertComponent = (ComponentContainer) component;
            }

            private Component getView(int index) {
                return convertComponent.getComponentAt(index);
            }

            private void clearPixelMapOnView() {
                for (int i = 0; i < convertComponent.getChildCount(); i++) {
                    ((Image) convertComponent.getComponentAt(i)).setPixelMap(null);
                }
            }
        }
    }

}
